﻿package com.iparticle {
	
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	import flash.utils.*;
	
	public class Particle extends MovieClip {
		
		// Constants:
		
		// Public Properties:
		public var alphaOutPercent:Number = .3; 
		public var alphaInPercent:Number = .3;
		public var xSpeed:Number = 0;
		public var ySpeed:Number = 0;
		public var gravity:Number = 0;
		public var endScale:Number = 1;
		public var orient:Boolean = false;
		
		// Private Properties:
		private var _originalLife:int = 0;
		private var _life:Number = 0;
		private var _alphaOutRate:Number;
		private var _alphaOutStartLife:Number;
		private var _alphaInRate:Number;
		private var _alphaInStartLife:Number;
		private var _scaleRate:Number;
		private var _lastPos:Point = new Point;
		private var _prevTime:int;
		// Initialization:
		public function Particle ( ) { 
			alpha = 0;
		}
	
		// Public Methods:
		public function set life ( $life : Number ) : void {
			_prevTime = getTimer();
			
			_originalLife = $life;
			_life = $life;
			
			//var mLife:Number = (_originalLife*1000)/ParticleEmitter.period;
			
			
			if(alphaInPercent > 0) {
				_alphaInRate = 1/((_life*alphaInPercent)*ParticleEmitter.fps);
			} else {
				_alphaInRate = 1;
			}
			
			_alphaInStartLife = _life - _life*alphaInPercent;
			
			_alphaOutRate = 1/((_life - _life*alphaOutPercent)*ParticleEmitter.fps);
			_alphaOutStartLife = _life - _life*alphaOutPercent;
			
			_scaleRate = (endScale-scaleX)/ParticleEmitter.fps;
			
			_lastPos.x = x;
			_lastPos.y = y;
			
			if(_scaleRate == 0 && !orient){
				cacheAsBitmap = true;
			}
		}
		
		public function get life ( ) : Number {
			return _life;
		}
		
		public function update ( ) : void {
			if(_life > 0){
				var currentTime:int = getTimer();
				var elapsedTime:int = currentTime-_prevTime;
				_prevTime = currentTime;
				_life -= elapsedTime*.001;
				var currentRate:Number = elapsedTime/ParticleEmitter.mpf;
								
				x += xSpeed*currentRate;
				y += ySpeed*currentRate;
				scaleX += _scaleRate*currentRate;
				scaleY += _scaleRate*currentRate;
				ySpeed += gravity*currentRate;
				//y += gravity;
				
				if(_life <= _alphaOutStartLife){
					alpha -= _alphaOutRate*currentRate;
				} else if(_life > _alphaInStartLife){
					alpha += _alphaInRate*currentRate;
				} else if(alphaInPercent == 0){
					alpha = 1;
				}
				
				if(orient){
					
					var angle:Number = ParticleMath.angleFromPoints(_lastPos, new Point(x, y));
					rotation = angle;
					_lastPos.x = x;
					_lastPos.y = y;
				}
				
			} else {
				killParticle();
			}
			
		}
		// Protected Methods:
		protected function killParticle ( ) : void {
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
	}
	
}